package com.raywang.pos.ui;

import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
/**
 * 处理了一些公共地方的activity基类
 * 本activity主要是针对Fragment操作进行了一些优化
 * (本类未进行详细测试)
 * @author Ray
 * @version 1.0
 */
@SuppressLint("UseSparseArrays")
public class BaseActivity extends Activity implements OnClickListener{

	
	/** 最后一个显示的Fragment,替换时就是会移除这个Fragment,和父容器一一对应*/
	private HashMap<Integer, Fragment> lastReplaceFragment = new HashMap<Integer, Fragment>();
	
	protected void onCreate(Bundle savedInstanceState,int layoutId) {
		super.onCreate(savedInstanceState);
		setContentView(layoutId);
		iniFragment();
	}
	
	/**
	 * 初始化Fragment
	 */
	protected void iniFragment() {
		
	}
	
	/**
	 * 替换一个Fragment，不过和原本的FragmentTransaction替换不一样的是，
	 * 这个替换方法只会移除上一个fragment
	 * @param containerViewId 父容器的id
	 * @param fragment Fragment对象
	 */
	public void replace(int containerViewId,Fragment fragment){
		FragmentManager fm = getFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		if(lastReplaceFragment.containsKey(containerViewId)){
			ft.remove(lastReplaceFragment.get(containerViewId));
		}
		if(fragment != null && !fragment.isAdded()){
			ft.add(containerViewId,fragment);
			lastReplaceFragment.put(containerViewId, fragment);
		}

		ft.commit();
	}

    public void replaceToBack(int containerViewId,Fragment fragment){
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if(lastReplaceFragment.containsKey(containerViewId)){
            ft.remove(lastReplaceFragment.get(containerViewId));
        }
        if(fragment != null && !fragment.isAdded()){
            ft.add(containerViewId,fragment);
            ft.addToBackStack(null);
            lastReplaceFragment.put(containerViewId, fragment);
        }

        ft.commit();
    }
	
	/**
	 * 添加一个Fragment，此方法并不会移除上一个Fragment，而是叠加进去
	 * @param containerViewId
	 * @param fragment
	 */
	public void add(int containerViewId,Fragment fragment){
		FragmentManager fm = getFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		if(!fragment.isAdded()){
			ft.add(containerViewId,fragment);
		}
		ft.commit();
	}
	
	/**
	 * 移除指定的Fragment
	 * @param containerViewId
	 * @param fragment
	 */
	public void remove(int containerViewId,Fragment fragment){
		FragmentManager fm = getFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.remove(fragment);
		ft.commit();
	}

	public void onClick(View v) {
		v.setEnabled(false);
		click(v.getId());
		v.setEnabled(true);
	}
	
	protected void click(int id) {

	}
}
